import json
from itertools import product
from goods.models import Product
from django.shortcuts import render
from buyHigh.settings.settings_dev import BASE_URL
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet
from .models import Sku,skuAndAttribute,attribute
from buyHigh.utils.buyHighResponse import APIResponse
from .serializer import SkuSerializer,attributeSerializer,singleSkuSerializer
from .utils import get_spec_list
from order.models import Order
# Create your views here.
class skuView(GenericViewSet):
    queryset = Sku.objects.all()
    serializer_class = SkuSerializer
    # 获取该商品的所有sku列表
    @action(methods=['get'],detail=False,url_path="get_sku/(?P<pk>\d+)")
    def get_sku(self,request,*args,**kwargs):
        # 前端传递goods_id，通过goods_id获取sku列表
        print('进入get——sku')
        product_id=kwargs.get("pk")
        skuQuerySet=Sku.objects.filter(product_id=product_id)
        ser=SkuSerializer(skuQuerySet,many=True)
        attr_queryset=skuAndAttribute.objects.filter(sku__in=skuQuerySet).values('attribute')
        all_attributes=attribute.objects.filter(id__in=attr_queryset)
        spec_list = get_spec_list(all_attributes)
        product_obj=Product.objects.get(id=product_id)
        return APIResponse(data={'_id':product_id,'name':product_obj.name,'goods_thumb':BASE_URL+product_obj.cover.url,'sku_list':ser.data,'spec_list':spec_list},status=200,statusCode=200,code=200)
    # 通过sku_id获取sku信息，结算时获取sku所使用
    @action(methods=['get'],detail=False)
    def get_sku_by_id(self,request,*args,**kwargs):
        # 注意拿到的是json字符串
        print('进入了get_sku_by_id')
        sku_id_list=request.GET['sku_id_list']
        print(json.loads(sku_id_list),'sku_id_list')
        # 转为python列表
        try:
            sku_id_list=json.loads(sku_id_list)
            skuQuerySet = Sku.objects.filter(id__in=sku_id_list)
        except:
            skuQuerySet = Sku.objects.filter(id=sku_id_list)
        ser=singleSkuSerializer(skuQuerySet,many=True)
        return APIResponse(statusCode=200,code=200,data=ser.data)
    @action(methods=['get'],detail=False)
    def get_sku_by_order_number(self,request,*args,**kwargs):
        order_number=request.GET['order_number']
        order_queryset=Order.objects.filter(order_number=order_number)
        sku_list=[]
        for order in order_queryset:
            sku_list.append(order.sku)
        ser=singleSkuSerializer(sku_list,many=True)
        return APIResponse(statusCode=200,data=ser.data)






